using System.IO;
using System.Security.Cryptography;
using System.Text;
using System;
using UnityEditor;
using UnityEngine;
using UnityEngine.UI;

public static class EditorUtil
{
    //todo 后续需要迁移统一管理
    public static string imgCsv = Path.GetFullPath("../Excel/excel/Image.csv");
    public static string modelCsv = Path.GetFullPath("../Excel/excel/Model.csv");

    [MenuItem("工具集合Z/程序工具/给项目内所有Button挂上点击音效脚本", priority = 202)]
    private static void AddOnButtonClickHandle()
    {
        // 获取所有 prefab 文件路径
        string[] allPrefabs = AssetDatabase.FindAssets("t:Prefab", new[] { "Assets/Res/static" }); // 替换为实际目录

        foreach (string prefabGUID in allPrefabs)
        {
            // 获取 prefab 路径
            string prefabPath = AssetDatabase.GUIDToAssetPath(prefabGUID);
            GameObject prefab = AssetDatabase.LoadAssetAtPath<GameObject>(prefabPath);

            if (prefab != null)
            {
                // 查找 prefab 中的所有 Button 组件
                Button[] buttons = prefab.GetComponentsInChildren<Button>(true);
                foreach (Button button in buttons)
                {
                    // 检查是否已经挂载 OnButtonClickHandle 脚本

                }

                // 保存 prefab 更改
                EditorUtility.SetDirty(prefab);
            }
        }

        // 应用所有更改
        AssetDatabase.SaveAssets();
        AssetDatabase.Refresh();

        Debug.Log("已将 OnButtonClickHandle 脚本添加到所有 Button 组件上。");
    }


    public static void SpriteToExcel(string spritePath)
    {
        if (!File.Exists(imgCsv))
        {
            throw new Exception($"找不到文件 {imgCsv}，请创建表格");
        }
        if (string.IsNullOrEmpty(spritePath) || !File.Exists(spritePath))
        {
            throw new Exception("路径为空");
        }
        if (!spritePath.Contains("Assets/Res/dynamic"))
        {
            throw new Exception("文件需要在指定目录(Assets/Res/dynamic)下");
        }
        string extension = Path.GetExtension(spritePath).ToLower();
        if (extension != ".png" && extension != ".jpg" && extension != ".jpeg")
        {
            throw new Exception("只能使用图片文件");
        }

        string resourceId = Path.GetFileNameWithoutExtension(spritePath);
        string resourceFile = Path.GetFileName(spritePath);
        string type = string.Empty; // 示例图集路径


        // 如果 sourceDirectory 的父级文件夹名叫 Texture 则 resourceAtlas 为 string.Empty
        if (spritePath.Contains("texture"))
        {
            type = string.Empty;
        }
        // 如果 spritePath 包含一个叫 Dynamic 的文件夹则 resourceAtlas 为 XXX/Dynamic/Atlas/文件的父级文件夹名.atlas
        else if (spritePath.Contains("Assets/Res/dynamic/Sprite"))
        {
            type = "atlas";
        }
        else
        {
            throw new Exception($"文件 {spritePath}，不在项目规定路径下");
        }

        string resourcePath = spritePath; // 资源路径

        string newFileMd5 = GetFileMd5(spritePath);
        string[] lines = File.ReadAllLines(imgCsv);
        for (int i = 0; i < lines.Length; i++)
        {
            var line = lines[i];
            var values = line.Split(',');

            if (values[1] == resourceId)
            {
                // 通过 resourcePath 获取文件比对两个文件是否是同一个
                string existingFilePath = values[4];
                string existingFileMd5 = newFileMd5;
                if (File.Exists(existingFilePath))
                {
                    existingFileMd5 = GetFileMd5(existingFilePath);
                }
                if (existingFileMd5 == newFileMd5)
                {
                    // md5相同覆盖内容
                    lines[i] = $",{resourceId},{resourceFile},{type},{resourcePath},";
                    File.WriteAllLines(imgCsv, lines, Encoding.UTF8);
                    Debug.Log($"id:{resourceId} 被覆盖 fileName:{resourceFile} atlasPath:{type} resourcePath:{resourcePath} ");
                    return;
                }
                else
                {
                    throw new Exception($"ID {resourceId} 已存在相同key");
                }
            }
        }
        // 写入CSV文件
        using (var writer = new StreamWriter(imgCsv, true, new UTF8Encoding(false)))
        {
            writer.WriteLine($",{resourceId},{resourceFile},{type},{resourcePath},");
            Debug.Log($"新写入 id:{resourceId} fileName:{resourceFile} atlasPath:{type} resourcePath:{resourcePath} ");
        }
    }

    public static void ModelToExcel(string modelPath)
    {
        if (!File.Exists(modelCsv))
        {
            throw new Exception($"找不到文件 {modelCsv}，请创建表格");
        }
        if (string.IsNullOrEmpty(modelPath) || !File.Exists(modelPath))
        {
            throw new Exception("路径为空");
        }
        if (!modelPath.Contains("Assets/Res/dynamic/"))
        {
            throw new Exception("文件需要在指定目录(Assets/Res/dynamic/)下");
        }
        string extension = Path.GetExtension(modelPath).ToLower();
        if (!(extension.Contains(".asset") || extension.Contains(".prefab")))
        {
            throw new Exception("只能使用模型或asset资源");
        }

        string resourceId = Path.GetFileNameWithoutExtension(modelPath);
        string resourcePath = modelPath; // 资源路径

        string newFileMd5 = GetFileMd5(modelPath);
        string[] lines = File.ReadAllLines(modelCsv);
        for (int i = 0; i < lines.Length; i++)
        {
            var line = lines[i];
            var values = line.Split(',');

            if (values[1] == resourceId)
            {
                // 通过 resourcePath 获取文件比对两个文件是否是同一个
                string existingFilePath = values[2];
                string existingFileMd5 = newFileMd5;
                if (File.Exists(existingFilePath))
                {
                    existingFileMd5 = GetFileMd5(existingFilePath);
                }
                if (existingFileMd5 == newFileMd5)
                {
                    // md5相同覆盖内容
                    lines[i] = $",{resourceId},{resourcePath},";
                    File.WriteAllLines(modelCsv, lines, Encoding.UTF8);
                    Debug.Log($"modelId:{resourceId} 被覆盖 resourcePath:{resourcePath} ");
                    return;
                }
                else
                {
                    throw new Exception($"ID {resourceId} 已存在相同key");
                }
            }
        }
        // 写入CSV文件
        using (var writer = new StreamWriter(modelCsv, true, new UTF8Encoding(false)))
        {
            writer.WriteLine($",{resourceId},{resourcePath},");
            Debug.Log($"新写入 modelId:{resourceId} resourcePath:{resourcePath} ");
        }
    }

    private static string GetFileMd5(string filePath)
    {
        using (var md5 = MD5.Create())
        {
            using (var stream = File.OpenRead(filePath))
            {
                var hash = md5.ComputeHash(stream);
                return BitConverter.ToString(hash).Replace("-", "").ToLowerInvariant();
            }
        }
    }

    [MenuItem("Assets/BoxGame/将图片导入csv")]
    public static void Export()
    {
        if (Selection.objects == null || Selection.objects.Length == 0)
        {
            Debug.LogError("未选中文件");
            return;
        }

        foreach (var item in Selection.objects)
        {
            string path = AssetDatabase.GetAssetPath(item);
            try
            {
                EditorUtil.SpriteToExcel(path);
            }
            catch (Exception e)
            {
                Debug.LogError("导入失败：" + path);
                Debug.LogError(e);
            }
        }
        Debug.Log("所有选中文件已处理完毕");
    }
    [MenuItem("Assets/BoxGame/将模型导入csv")]
    public static void ExportToModel()
    {
        if (Selection.objects == null || Selection.objects.Length == 0)
        {
            Debug.LogError("未选中文件");
            return;
        }
        foreach (var item in Selection.objects)
        {
            string path = AssetDatabase.GetAssetPath(item);
            try
            {
                EditorUtil.ModelToExcel(path);
            }
            catch (Exception e)
            {
                Debug.LogError("导入失败：" + path);
                Debug.LogError(e);
            }
        }
        Debug.Log("所有选中模型已处理完毕");
    }
}